package com.joker;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import static com.joker.ZookeeperConstant.ZK_ADDRESS;

public class CuratorExample {
    private static final String ZK_PATH = "/test-curator";

    public static void main(String[] args) throws Exception {
        // 创建连接
        CuratorFramework client = CuratorFrameworkFactory.newClient(
                ZK_ADDRESS,
                new ExponentialBackoffRetry(1000, 3)
        );

        client.start();
        System.out.println("Curator客户端已启动");

        // 创建节点
        client.create().creatingParentsIfNeeded().forPath(ZK_PATH, "初始数据".getBytes());

        // 读取数据
        byte[] data = client.getData().forPath(ZK_PATH);
        System.out.println("节点数据: " + new String(data));

        // 设置节点监听
        NodeCache nodeCache = new NodeCache(client, ZK_PATH);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                ChildData currentData = nodeCache.getCurrentData();
                if (currentData != null) {
                    System.out.println("节点发生变化，新数据: " + new String(currentData.getData()));
                }
            }
        });
        nodeCache.start();

        // 更新数据
        client.setData().forPath(ZK_PATH, "更新后的数据".getBytes());

        // 等待一段时间观察监听效果
        Thread.sleep(3000);

        // 清理
        client.delete().forPath(ZK_PATH);
        nodeCache.close();
        client.close();
    }
}